<?php

namespace Admin\Pages;

/**
 * Description of Index
 *
 * @author nofear
 */
class Mails extends Page {

    private $objectEntity = 'Mail';

    public function __construct() {
        parent::__construct();
        $this->view = new \System\Template('@admin/mails.twig');
        $this->view->pageName = 'Съобщения';
    }

    public function index() {
        $QB = $this->EntityManager->createQueryBuilder();

        $mails = $QB->select('o')
                ->from($this->projectEntityNamespace . $this->objectEntity, 'o')
                ->orderBy('o.id', 'DESC')
                ->getQuery()
                ->getResult();

        $Session = $this->getSession();
        if ($Session->have('message')) {
            $this->view->message = $Session->getMessage();
            $Session->removeMessage();
        }

        $this->view->mails = $mails;
    }

    public function view($id) {
        if (!$id) {
            $this->createNotFound('Такова известие не съществува!');
        }
        
        $Mail = $this->EntityManager->find($this->projectEntityNamespace . $this->objectEntity, $id);

        if (!$Mail) {
            $this->createNotFound('Такова известие не съществува!');
        }
        $this->view = new \System\Template('@admin/mailView.twig');
        $this->view->Mail = $Mail;
        
        $Mail->setIsNew(false);
        
        $this->EntityManager->persist($Mail);
        $this->EntityManager->flush();
    }

    public function delete($id) {
        $id = $this->sanitize($id);
        $Session = $this->getSession();

        $message['text'] = 'Възникна грешка!';
        $message['type'] = 'alert-danger';

        if ($id) {
            $Product = $this->EntityManager->find($this->projectEntityNamespace . $this->objectEntity, $id);

            if ($Product) {
                $this->EntityManager->remove($Product);
                $this->EntityManager->flush();

                $message['text'] = 'Известието е изтрито успешно.';
                $message['type'] = 'alert-success';
            }
        }

        $Session->setMessage($message);
        $this->redirect(\Shared\URLManager::getInstance()->createPath('admin_mails'));
    }

}
